/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useState } from "react";
import {
  Table,
  Input,
  Select,
  Button,
  Space,
  Row,
  Col,
  Pagination,
  Modal,
} from "antd";
import "./Store.scss";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";

const { Option } = Select;

// 导入StoreModal组件
import StoreModal from "./StoreModal";

// 仓库数据类型定义
interface StoreData {
  key?: string;
  storeCode: string;
  storeName: string;
  capacity: string;
  address: string;
  department: string;
  responsiblePerson: string;
  locationCount: string;
  status: string;
  operator: string;
  operateTime: string;
}

export default function Store() {
  // 状态管理
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentEditData, setCurrentEditData] = useState<StoreData | undefined>(
    undefined
  );
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 模拟仓库数据
  const generateStoreData = (): StoreData[] => {
    const statuses = ["启用", "停用", "已锁定"];
    const departments = [
      "部门一",
      "部门二",
      "部门三",
      "部门四",
      "部门五",
      "部门六",
      "部门七",
      "部门八",
      "部门九",
      "部门十",
    ];
    const responsiblePersons = [
      "嵇歆美",
      "溥雨柏",
      "宗政欣怡",
      "乌雅茉",
      "刑素怀",
      "星飞虎",
      "令乐",
      "苍冰蝶",
      "令骊丽泽",
      "刑景澄",
    ];
    const operators = [
      "曹曜",
      "九宾实",
      "应鹏鲲",
      "贝代卉",
      "乾娴雅",
      "错又菡",
      "萧文惠",
      "苦俊楚",
      "帖天蓝",
      "艾如波",
    ];

    const now = new Date();
    const dateStr = `${now.getFullYear()}-09-23 ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

    const data: StoreData[] = [];

    for (let i = 1; i <= 100; i++) {
      data.push({
        key: i.toString(),
        storeCode: `CKBH${Math.floor(Math.random() * 9000) + 1000}`,
        storeName: `仓库${i}`,
        capacity: "500",
        address: "河南省三门峡市卢氏县文化路956号",
        department: departments[(i - 1) % departments.length],
        responsiblePerson:
          responsiblePersons[(i - 1) % responsiblePersons.length],
        locationCount: `${Math.floor(Math.random() * 50) + 1}`,
        status: statuses[(i - 1) % statuses.length],
        operator: operators[(i - 1) % operators.length],
        operateTime: dateStr,
      });
    }

    return data;
  };

  // 将storeData改为状态，以便能够更新数据
  const [storeData, setStoreData] = useState<StoreData[]>(generateStoreData());

  // 分页数据
  const paginatedData = storeData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // 表格列定义
  const columns = [
    {
      title: "序号",
      key: "index",
      width: 60,
      render: (_: any, __: any, index: number) =>
        index + 1 + (currentPage - 1) * pageSize,
    },
    {
      title: "仓库编号",
      dataIndex: "storeCode",
      key: "storeCode",
      width: 100,
    },
    {
      title: "仓库名称",
      dataIndex: "storeName",
      key: "storeName",
      width: 100,
    },
    {
      title: "仓库容量/m³",
      dataIndex: "capacity",
      key: "capacity",
      width: 100,
    },
    {
      title: "仓库地址",
      dataIndex: "address",
      key: "address",
      width: 180,
    },
    {
      title: "库管部门",
      dataIndex: "department",
      key: "department",
      width: 100,
    },
    {
      title: "仓库主管",
      dataIndex: "responsiblePerson",
      key: "responsiblePerson",
      width: 80,
    },
    {
      title: "库位数量",
      dataIndex: "locationCount",
      key: "locationCount",
      width: 80,
    },
    {
      title: "仓库状态",
      dataIndex: "status",
      key: "status",
      width: 80,
      render: (status: string) => (
        <span
          style={{
            color:
              status === "启用"
                ? "#52c41a"
                : status === "停用"
                ? "#d9d9d9"
                : "#ff4d4f",
          }}>
          {status}
        </span>
      ),
    },
    {
      title: "操作人",
      dataIndex: "operator",
      key: "operator",
      width: 80,
    },
    {
      title: "操作时间",
      dataIndex: "operateTime",
      key: "operateTime",
      width: 150,
    },
    {
      title: "操作",
      key: "action",
      width: 100,
      render: (_: any, record: StoreData) => (
        <Space size="middle">
          <a className="edit-link" onClick={() => handleEdit(record)}>
            编辑
          </a>
          <a className="delete-link" onClick={() => handleDelete(record)}>
            删除
          </a>
        </Space>
      ),
    },
  ];

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 处理编辑操作
  const handleEdit = (record?: StoreData) => {
    setIsEdit(true);
    setIsModalVisible(true);
    // 如果有传入具体记录，则使用该记录
    if (record) {
      setTimeout(() => {
        setCurrentEditData(record);
      }, 0);
    }
    // 否则尝试使用选中行的数据
    else if (selectedRowKeys.length > 0) {
      const editData = storeData.find(
        (item) => item.key === selectedRowKeys[0]
      );
      if (editData) {
        setTimeout(() => {
          setCurrentEditData(editData);
        }, 0);
      }
    }
  };

  // 处理删除操作
  const handleDelete = (record?: StoreData) => {
    // 如果有传入具体记录，则使用该记录
    if (record) {
      Modal.confirm({
        title: "确认删除",
        content: `确定要删除仓库「${record.storeName}」吗？`,
        okText: "确定",
        cancelText: "取消",
        onOk: () => {
          // 删除逻辑
          setStoreData((prevData) =>
            prevData.filter((item) => item.key !== record.key)
          );
        },
      });
    }
    // 否则尝试使用选中行的数据
    else if (selectedRowKeys.length > 0) {
      const deleteData = storeData.find(
        (item) => item.key === selectedRowKeys[0]
      );
      if (deleteData) {
        Modal.confirm({
          title: "确认删除",
          content: `确定要删除仓库「${deleteData.storeName}」吗？`,
          okText: "确定",
          cancelText: "取消",
          onOk: () => {
            // 删除逻辑
            setStoreData((prevData) =>
              prevData.filter((item) => item.key !== deleteData.key)
            );
            setSelectedRowKeys([]);
          },
        });
      }
    }
  };

  // 处理新增操作
  const handleAdd = () => {
    console.log("新增仓库");

    setIsEdit(false);
    setCurrentEditData(undefined);
    setIsModalVisible(true);
  };

  // 处理表单提交
  const handleSubmit = (values: StoreData) => {
    console.log("表单值:", values);

    if (isEdit && currentEditData?.key) {
      // 编辑模式：更新现有数据
      setStoreData((prevData) =>
        prevData.map((item) =>
          item.key === currentEditData.key
            ? { ...values, key: currentEditData.key }
            : item
        )
      );
    } else {
      // 新增模式：添加新数据
      const newKey = (storeData.length + 1).toString();
      setStoreData((prevData) => [...prevData, { ...values, key: newKey }]);
    }

    // 重置状态
    setIsModalVisible(false);
    setIsEdit(false);
    setCurrentEditData(undefined);
  };

  return (
    <div className="store-management">
      <div className="store-content">
        {/* 搜索筛选区域 */}
        <div className="search-filter">
          <Row gutter={16} align="middle">
            <Col>
              <span style={{ marginRight: "8px" }}>仓库</span>
              <Input placeholder="请输入仓库名称/编号" style={{ width: 180 }} />
            </Col>
            <Col>
              <span style={{ marginRight: "8px" }}>仓库状态</span>
              <Select placeholder="请选择" style={{ width: 120 }}>
                <Option value="启用">启用</Option>
                <Option value="停用">停用</Option>
                <Option value="已锁定">已锁定</Option>
              </Select>
            </Col>
            <Col>
              <span style={{ marginRight: "8px" }}>库管部门</span>
              <Input placeholder="请输入" style={{ width: 120 }} />
            </Col>
            <Col>
              <span style={{ marginRight: "8px" }}>仓库主管</span>
              <Input placeholder="请输入" style={{ width: 120 }} />
            </Col>
            <Col>
              <Space>
                <Button className="reset-button">重置</Button>
                <Button type="primary" className="search-button">
                  查询
                </Button>
                <Button className="advanced-search-button">高级搜索</Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作按钮区域 */}
        <div className="action-buttons">
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}>
              删除
            </Button>
            <Button>启用</Button>
            <Button>停用</Button>
            <Button>锁定</Button>
          </Space>
        </div>

        {/* 仓库列表表格 */}
        <div className="store-table">
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={paginatedData}
            pagination={false}
            scroll={{
              x: "max-content",
              y: 400, // 设置表格内容区域的高度，超出时显示垂直滚动条
            }}
          />
        </div>

        {/* 分页区域 */}
        <div className="pagination">
          <div className="total-count">总 {storeData.length} 条</div>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={storeData.length}
            onChange={(page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `总 ${total} 条`}
            pageSizeOptions={["10", "20", "50", "100"]}
          />
        </div>

        {/* 编辑/新增弹窗 */}
        <StoreModal
          visible={isModalVisible}
          isEdit={isEdit}
          initialValues={currentEditData}
          onCancel={() => {
            setIsModalVisible(false);
            setIsEdit(false);
          }}
          onSubmit={handleSubmit}
        />
      </div>
    </div>
  );
}
